import {Component} from '@angular/core';
import {ActionSheetController, AlertController, IonicPage, NavController, NavParams} from 'ionic-angular';
import {Storage} from "@ionic/storage";
import {HttpClient} from "@angular/common/http";
import {AppUrl} from "../../../app/app.general";
import {AppConfig} from "../../../app/appConfig";
import {CommonService} from "../../../app/common.service";

/**
 *
 * @Author AileYoung on 2018/1/24
 */

@IonicPage()
@Component({
  selector: 'page-busifood-tableset',
  templateUrl: 'busifood-tableset.html',
})
export class BusifoodTablesetPage {
  private tableSite = {
    used: {name: '已开台', color: '#389cf4'},
    waitForClean: {name: '待清理', color: 'brown'},
    ordered: {name: '已预订', color: 'coral'},
    stopToUse: {name: '暂停使用', color: 'black'},
    Idle: {name: '空闲', color: '#41b883'}
  };

  private TableData:
    Array<{
    floorid:number,floor:string, show:boolean, tables:Array<{
      id: any, tablename: string, tablesize: string,tableSite: {
        name:any,
        color: string
      },
    }>,
  }>;

  deleteFloor(floorid,j){
    let confirm = this.alertCtrl.create({
      title: '删除楼层?',
      message: '楼层删除后餐台也会被删除，是否删除该楼层?',
      buttons: [
        {
          text: '不同意',
          handler: () => {
          }
        },
        {
          text: '同意',
          handler: () => {
            this.http.post(AppUrl.table.deleteFloor,{restId:localStorage.getItem('restaurantid'),floorId:floorid}).subscribe(data => {
              let temp:any = data;
              if (temp.code === 200){
                this.TableData.splice(j,1);
              }
              else {
                this.appConfig.presentToast(temp.msg);
              }
            },reject=>{
              this.commonServ.httpError(reject);
            });
          }
        }
      ]
    });
    confirm.present()
}

  constructor(public navCtrl: NavController, public navParams: NavParams, private alertCtrl: AlertController,
              private actionSheetCtrl: ActionSheetController, private storage: Storage,private http:HttpClient,private appConfig:AppConfig,private commonServ:CommonService) {
           this.TableData = [];
  }
  getData(){
    this.TableData=[];
    this.http.post(AppUrl.table.floortable,{userid:localStorage.getItem('userid')}).subscribe(data=>{
      let temp1:any=data;
      let temp:any[]=temp1.data;
      let floor:any=temp[0];
      let table:any=temp[1];

      let k=0;
      for(let f of floor){
        let ar=table.filter(e=>e.floorid==f.id);
        this.TableData.push({
          floorid:f.id,
          floor:f.floor,
          show:true,
          tables:[]
        });
        for(let i=0;i<ar.length;i++){
          this.TableData[k].tables.push({
            id: ar[i].id,
            tablename: ar[i].tableno,
            tablesize: ar[i].tablesize,
            tableSite: {
              name:ar[i].status,
              color: '#41b883'
            }
          });
        }
        k++;
      }
      // console.log ("iLength"+ this.iLength);
    });
  }


  ionViewDidLoad() {
    console.log('ionViewDidLoad BusifoodTablesetPage');
  }

  ionViewWillEnter() {
    console.log('是不是每次刷新界面就会出现!!!!!');
    console.log(this.TableData);

    this.getData();
  }

  addtable(floorid) {
    this.navCtrl.push('BusifoodTableContentSetPage',{floorid:floorid,callback:this.getdata});
  }

  getdata=(data)=>{
    return new Promise((resolve,reject)=>{
      console.log(data);
      let index=this.TableData.findIndex(e=>e.floorid==data.floorid);
      this.TableData[index].tables.push({
        id: data.tableid,
        tablename: data.tablename,
        tablesize: data.tablesize,
        tableSite: {
          name:'空闲',
          color: '#41b883'
        }
      });


      // this.saveTableDataStorage();
      resolve();
    });
  }

  changeState(item) {
    item.show = !item.show;
  }

  deleteRoom(floorid,tableid,i,j){
    let alert = this.alertCtrl.create();
    alert.setTitle('删除餐台');
    alert.setMessage('确认要删除该餐台吗？');
    alert.addButton('取消');
    alert.addButton({
      text: '立即删除',
      handler: data => {
        this.appConfig.presentLoading('正在删除...');
        this.http.post(AppUrl.table.deletetable,{id:tableid}).subscribe(data=>{
          let temp:any = data;
          if (temp.code === 200){
            // this.TableData[floorid-1].tables.splice(i, 1);
            this.TableData[j].tables.splice(i, 1);
          }
          else {
            this.appConfig.presentToast(temp.msg);
          }
          this.appConfig.loader.dismiss();
        },reject=>{
          this.commonServ.httpError(reject);
          this.appConfig.loader.dismiss();
        });
      }
    });
    alert.present();
  }
  // saveTableDataStorage() {
  //   this.storage.set('TableData', this.TableData);
  // }

  addFloor(){
    let alert=this.alertCtrl.create({
      title:'添加楼层信息',
      message:'请输入楼层或餐厅区域信息',
      inputs:[{
        name:'floorname',
        placeholder:'楼层或包厢名称'
      }],
      buttons: [
        {
          text: '取消',
          handler: data => {
            console.log('Cancel clicked');
          }
        },
        {
          text: '确认',
          handler: data1 => {
            if(data1.floorname.trim() == ''){
              return;
            }
            this.http.post(AppUrl.table.addfloor,{floor:data1.floorname}).subscribe(data=>{
              console.log(data);
              let temp:any=data;
              this.TableData.push({
                floorid:temp.data,
                floor:data1.floorname,
                show:false,
                tables:[]
              });
            });
          }
        }
      ]
    });
    alert.present();
  }
}
